package cn.edu.tjufe.llp.tin.service.part04;

import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.tjufe.llp.tin.common.RecordNotFoundException;
import cn.edu.tjufe.llp.tin.dto.part04.BookDto;
import cn.edu.tjufe.llp.tin.mapstruct.BookMapper;
import cn.edu.tjufe.llp.tin.model.bsc.BscBook;
import cn.edu.tjufe.llp.tin.repository.bsc.BscBookRepository;

@Service
@Transactional
public class BookServiceImpl implements BookService{
	
	@Autowired
	private BscBookRepository bscBookRepository;

	@Transactional(readOnly = true)
	@Override
	public BookDto selectById(Long id) {
		BscBook entity = bscBookRepository.findById(id).orElseThrow(() -> new RecordNotFoundException());
		return BookMapper.INSTANCE.toBookDto(entity);
	}

	@Transactional(readOnly = true)
	@Override
	public List<BookDto> selectList(String name, String author, String publisher, LocalDate begin, LocalDate end) {
		//List<BscBook> entities = bscBookRepository.findByNameAndAuthor(name, author);
		List<BscBook> entities = bscBookRepository.findAll(BookSpecifications.normalCondition(name, author, publisher, begin, end));
		return BookMapper.INSTANCE.toBookDtoList(entities);
	}

	@Override
	public long insert(BookDto book) {
		BscBook entity = BookMapper.INSTANCE.ToBscBook(book);
		return bscBookRepository.save(entity).getId();
	}

	@Override
	public long update(BookDto book, Long id) {
		BscBook entity = bscBookRepository.findById(id).orElseThrow(() -> new RecordNotFoundException());
		BookMapper.INSTANCE.updateModel(book, entity); 	// 整体更新（排除掉ignore=true的属性）
		bscBookRepository.save(entity);
		
		return id;
	}

	@Override
	public int deleteById(Long id) {
		bscBookRepository.deleteById(id);
		return 0;
	}

	@Override
	public int deleteByIds(Long[] ids) {
		// bscBookRepository.deleteAllById(() -> Arrays.stream(ids).iterator());	// 针对基本数据类型long[]
		bscBookRepository.deleteAllById(Arrays.asList(ids));
		return 0;
	}

}
